<template>
	
	<view>
		<view class="add-btn" @click="addPrint()" >
			<uni-icons type="plusempty" size="40" color="#007AFF"  ></uni-icons>
		</view>
		<movable-area class="box">
			<view class="pro-body">
				<view class="fixed-header">
					<view class="uni-form-item uni-column">
						<view class="search-box">
							<input class="uni-input" confirm-type="search" placeholder="托盘单号"
							 placeholder-class="placeholder-style"   v-model="billNo"
		
								@confirm="onSearch" />
							<view class="search-icon" @click="onSearch">
								  <uni-icons type="search" size="40"></uni-icons>
							</view>
						</view>
						
					</view>
				</view>
				<view class="uni-form-list">
					<scroll-view scroll-y="true" class="scroll" 
					@scrolltolower="handleScrolltolower" refresher-enabled
						@refresherrefresh="handleRefresherrefresh" :refresher-triggered="refresherTriggered">
						<template v-if="motMap.receiveList && motMap.receiveList.length > 0">
							<uni-swipe-action>
							
								<uni-swipe-action-item v-for="item in motMap.receiveList">
									<view class="panel" 
										:style="{ backgroundColor: item.boxColor }">
										<view class="panel_title" :class="{error: item.error}">
											<view class="panel_title_left">{{ item.trayno }}</view>
											<!-- 右上角按钮 -->
											<!-- <button type="primary" size="mini" class="print-btn" @click="handlePrint(item)">打印</button> -->
											<!-- <view class="panel_title_right">{{ item.orgName }}</view> -->
										</view>
										<view class="panel_content">
											<view class="flex-list">
												
												<view class="flex-row">
												  <view class="flex-title">件号：</view>
												  <view class="flex-content">{{ item.fspecification }}</view>
												</view>
												<view class="flex-row" v-if="item.fmaterialname">
												  <view class="flex-title">物料名称：</view>
												  <view class="flex-content">{{ item.fmaterialname }}</view>
												</view>
												<view class="flex-row" >
												  <view class="flex-title">工单号：</view>
												  <view class="flex-content">{{ item.mobillno }}</view>
												</view>
												<view class="flex-row" v-if="item.flot">
												  <view class="flex-title">批号：</view>
												  <view class="flex-content">{{ item.flot }}</view>
												</view>
												<view class="flex-row" >
												  <view class="flex-title">数量：</view>
												  <view class="flex-content">{{ item.finfactqty }}</view>
												</view>
												<view class="flex-row" v-if="item.createtime">
												  <view class="flex-title">创建日期：</view>
												  <view class="flex-content">
												  	<uni-dateformat :date="item.createtime" format="yyyy年MM月dd日">
												  	</uni-dateformat>
												  </view>
												</view>
											</view>
											<button class="print-btn" @click="handlePrint(item)">打印</button>
										</view>
									</view>
								</uni-swipe-action-item>
								
								<!-- 加载 -->
								<uni-load-more
									:status="motMap.pageConfig.bottomLoading ? 'loading' : motMap.pageConfig.bottomEnd ? 'noMore' : 'more'">
								</uni-load-more>
							</uni-swipe-action>
						</template>
						<!-- <uni-empty-info v-else label="暂无任务信息"></uni-empty-info> -->
					</scroll-view>
			
					<!-- 扫码 -->
					<movable-view class="page-scanning" :x="x" :y="y" direction="all" @change="onChange" @click="getTaskInfoScanning()" out-of-bounds="false">
						<i class="iconfont icon-saomiao page-scanning-icon"></i>
					</movable-view>
				</view>
			
			</view>
		</movable-area>
		<!-- 扫描托盘 -->
		<tray-popup ref="trayPopupRef" @success="trayScanningScuess"></tray-popup>
		<!-- 获取托盘信息 -->
		<GetTrayUpdate ref="trayRef" ></GetTrayUpdate>
		
		
	</view>
</template>

<script>
	import {getProPlanisDetail,
		getJijiaTray,
	getTray,
	getSerial,
	updateJijiaTray,
	getMacByUuid
	} from '@/utils/api.js';
	import TaskOrder from '../../components/popup/task-order.vue';
	import trayPopup from '../../components/popup/trayPopup.vue'
	import GetTrayUpdate from "../pop/get_tray_update.vue"
	import {printContect,
		printQRCode,
		printData,
		safePrint,
		printVerticalLabelJiJia,
		printTextAndQRCode} from '@/utils/print.js'
	
	export default {
		components: {
			trayPopup,
			TaskOrder,
			GetTrayUpdate

		},
		data() {
			return {
				x:0,
				y:0,
				motMap: {
					receiveList: [],
					pageConfig: {
						bottomEnd: false,
						bottomLoading: true
					}
				},
				header:{},
				detail:[],
				refresherTriggered: false,
				_refresherTriggered: false,
				billNo: '', // 订单搜索框的值 

			};
		},
		methods: {
				// 申请 Android 蓝牙权限
			    requestBluetoothPermission(callback) {
			        if (plus.os.name !== "Android") {
			            callback(true); // iOS 直接返回
			            return;
			        }
			
			        const permissions = [
			            "android.permission.BLUETOOTH_SCAN",
			            "android.permission.BLUETOOTH_CONNECT",
			            "android.permission.ACCESS_FINE_LOCATION"
			        ];
			
			        const main = plus.android.runtimeMainActivity();
			        const PackageManager = plus.android.importClass("android.content.pm.PackageManager");
			        const ActivityCompat = plus.android.importClass("androidx.core.app.ActivityCompat");
			
			        let allGranted = true;
			
			        for (let i = 0; i < permissions.length; i++) {
			            const perm = permissions[i];
			            const result = ActivityCompat.checkSelfPermission(main, perm);
			            if (result !== PackageManager.PERMISSION_GRANTED) {
			                allGranted = false;
			                break;
			            }
			        }
			
			        if (allGranted) {
			            callback(true);
			            return;
			        }
			
			        // 请求权限
			        ActivityCompat.requestPermissions(main, permissions, 1);
			
			        // 简单处理：延迟一会儿再假设用户已经同意（实际可以用 plus.android.requestPermissionsResult 监听）
			        setTimeout(() => {
			            callback(true);
			        }, 500);
			    },
			forceFocus(e) {
			    this.$nextTick(() => {
			      e.target.focus()
			    })
			  },
			//打印生产日期，件号，数量，指令单号，涂成号(二维码显示托盘号)
			handlePrint(item){
				//获取生产日期和涂成号
				getSerial({'trayNo':item.trayno,'fspecification':item.fspecification}).then(res =>{
				
					let values = {
						// '件号': item.fspecification,
						'批号':res.data.data.flot,
						'数量' : item.finfactqty,
						'制令' : item.mobillno,
						'途程' : res.data.data.serialNo
					};
					safePrint()//校验打印机是否连接
					printVerticalLabelJiJia(item.fspecification,values,item.trayno)
					
					//打印成功后修改单据状态
					updateJijiaTray({id:item.id}).then(res =>{
						this.billNo = ''
						this.initData()
					})
				})

			},
			addPrint(){
				let uuid = plus.device.uuid;
				//获取打印机mac
				getMacByUuid({uuid:uuid}).then(res => { 
					if (res.data.status === 200){
						const macAddress = res.data.data.macAdress
						this.requestBluetoothPermission((granted) => {
							if (!granted) {
								uni.showToast({ title: '蓝牙权限未授权', icon: 'none' });
								return;
							}
							const printModule = uni.requireNativePlugin('PrintModuleCPCL');
							// const macAddress = '6C:C1:47:01:31:75'; // 替换成你的打印机MAC
							printContect(macAddress)
					
						});
					}
				})
			},
			onChange(e) {
				this.x = e.detail.x
				this.y = e.detail.y
			},
			/**
			 * 扫码
			 */
			getTaskInfoScanning() {
				this.$refs.trayPopupRef.open()
			},
			trayScanningScuess(e){
				let _this = this;
				this.billNo = e;
				this.initData()
			},
			
			handleScanSuccess(scanVal) {
				this.billNo = scanVal

				this.taskScanningSucess()
			},
			/**
		  * 订单号日期搜索
			 */
			onSearch() {
				this.initData({
					billNo: this.billNo,

				});
			},
			onChongzhi() {
				this.billNo = '';
			},

			/**
			 * 重置页数
			 */
			reset() {
				this.motMap.pageConfig.pageIndex = 0
			},


			/** 上滑加载 */
			handleScrolltolower() {
				if (this.motMap.pageConfig.bottomEnd) return
		
				this.initData()
			},
			/**
			 * 下拉刷新数据
			 */
			handleRefresherrefresh() {
				if (this._refresherTriggered) {
					return;
				}
				// 界面下拉触发，triggered可能不是true，要设为true
				if (!this.refresherTriggered) {
					this.refresherTriggered = true;
				}
				this.reset();
				this._refresherTriggered = true;
				this.motMap.pageConfig.bottomEnd = false;

				// 调用 initData 方法并确保在完成后重置 refresherTriggered 状态
				this.initData().then(() => {
					this.refresherTriggered = false;
					this._refresherTriggered = false;
				}).catch(error => {
				
					this.refresherTriggered = false;
					this._refresherTriggered = false;
				});
			},
			initData({
				billNo = ''
			} = {}) {
				return new Promise((resolve, reject) => {
					getJijiaTray({
						billNo: this.billNo || ""
					}).then(res => {
						if (res.data.status !== 200) {
							return;
						}
					
						
						this.motMap.receiveList = res.data.data.dataList
		
					
						this.motMap.pageConfig.bottomEnd = true;
						
						this.motMap.pageConfig.bottomLoading = false;
						this.loading = false;
						this.refresherTriggered = false;
						this._refresherTriggered = false;
						

						resolve();
					}).catch(err => {
						
						reject(err);
					});
				});
			},
			onSearch() {
				this.motMap.pageConfig.pageIndex = 0; // 重置分页索引
				this.initData({
					billNo: this.billNo
				});
			
			},


		},
		onLoad() {
		},
		mounted() {
			let self = this;
			this.initData()
		
		},
		//移除监听时间
		onUnload() {
			uni.$off('update')
		}
	};
</script>


<style lang="scss" scoped>
	@import "../../static/css/common";
	.box{
			width: 99vw;
			height: 99vh;
			}
		.pro-body {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			display: flex;
			flex-direction: column;
			background-color: #ffffff;
	
		}
	
		.fixed-header {
			position: fixed;
			top:40px;
			left: 0;
			right: 0;
			// z-index: 100;
			background-color: #ffffff;
			height: 80px;
			
		}
		.search-box {
			display: flex;
			width: 74%;
			align-items: center;
			border: 1px solid #000000;
			margin-left: 10px;
			// margin-top: 5px;
		    height: 55px;
		}
	        .search-box input {
	            flex: 1;
	            border: none;
	            outline: none;
	            padding: 0 12px;
	            font-size: 40px; /* 增大字体 */
	            height: 100%;
	            color: #333;
	        }
	        
	    
		.uni-input {
			flex: 1;
			padding: 10px;
			border: none;
			outline: none;
		
		}
		
		.search-icon {
			cursor: pointer;
			// z-index: 999;
		}
		
	/* 新增placeholder-class的样式 */
	.placeholder-style {
	    font-size: 20px !important;
	    color: #999 !important;
	}
	
	/* 面板样式 - 消除所有空隙 */
	/* 优化后的面板样式 - 确保分隔线生效且零空隙 */
	.panel {
	  height: 100%;
	  padding: 0; /* 清除内间距 */
	  margin: 0; /* 清除外间距 */
	  border-radius: 0;
	  background-color: #ffffff;
	  position: relative; /* 为伪元素分隔线定位准备 */
	  box-sizing: border-box; /* 防止边框影响布局 */
	}
	
	/* 使用伪元素实现加粗分隔线（更可控） */
	.panel::after {
	  content: "";
	  display: block;
	  position: absolute;
	  left: 0;
	  bottom: -3px; /* 精确控制位置 */
	  width: 100%;
	  height: 4px; /* 分隔线粗细 */
	  background-color: #9c9c9c; /* 分隔线颜色 */
	}
	
	  .panel_title {
	    display: flex;
	    justify-content: space-between;
	    font-size: 90px; /* 增大标题字号 */
	    font-weight: bold;
	    margin-bottom: 2px; /* 减少标题与内容的间距 */
	  }
		.panel_title_left {
		  font-size: 26px !important; /* 增大字体并添加!important确保覆盖 */
		  font-weight: bold;
		  color: #333;
		  flex: 1;
		}
		/* 新增：统一调整内容字体 */
	 .flex-list {
		    display: flex;
		    flex-direction: column;
		  }
		  .flex-row {
		    display: flex;
		    flex-direction: row;
		    margin-bottom: 2px; /* 行间距，根据需求调整 */
		    align-items: flex-start; /* 顶部对齐 */
		  }
		/* 新增：统一调整内容字体 */
		.flex-title{
			white-space: nowrap;
			font-size: 20px !important; /* 统一设置标签和内容字体 */
			line-height: 1.2; /* 缩小行高 */
			color: #000000 !important; 
		}
		.flex-content {
			word-break: break-all;
		  font-size: 20px !important; /* 统一设置标签和内容字体 */
		  line-height: 1.2; /* 缩小行高 */
		  color: #000000 !important; 
		}
		/* 调整列表项间距 */
		.flex-list {
		  gap: 1px; /* 缩小标签与内容的间距 */
		}
		.uni-form-item {
			display: flex;
			align-items: center;
			margin-bottom: 10px;
			width: 100%;
		}
	
	
		.scroll-container {
			flex: 1;
			overflow: hidden;
			overflow-y: auto;
			-webkit-overflow-scrolling: touch;
			/* 支持 iOS 上的平滑滚动 */
	
		}
	
		.scroll {
			padding-top: 80px;
			/* 使用 padding-top 替代 margin-top */
			// margin-bottom: px;
			/* 根据底部的高度调整 */
			height: calc(116vh - 160px - 1px);
			/* 根据需要调整高度 */
			position: relative;
			/* 避免使用 fixed */
			overflow-y: auto;
			/* 确保内容可以垂直滚动 */
		}
			.add-btn{
				  position: fixed;
				  top: 10px;  /* 根据 fixed-header 高度微调 */
				  right: 15px;
			
				z-index: 9999; /* 保证在最上层 */
				cursor: pointer;
				background-color: rgba(255, 255, 255, 0.001); /* 增加可点区域 */
			}
	.panel_title {
	  display: flex;
	  justify-content: space-between; /* 左右分布 */
	  align-items: center;
	}
	
	// .print-btn {
	//   padding: 0 20rpx;
	//   height: 50rpx;
	//   width: 100px;
	//   line-height: 50rpx;
	//   font-size: 26rpx;
	// }
	
		.print-btn {
		  margin-left: 10px;
		  height: 28px;
		  line-height: 28px;
		  padding: 0 12px;
		  font-size: 14px;
		  background-color: #409EFF; /* 蓝色按钮 */
		  color: #fff;
		  border-radius: 6px;
		}
</style>
